using System;
using System.IO;
using System.Reflection;
using Microsoft.Practices.ObjectBuilder2;

namespace Common.Unity.Extensions.Serialization
{
	public class AssemblyStreamResolver : IStreamResolver
	{
		readonly string assemblyName;
		readonly string resourceName;

		public AssemblyStreamResolver( string assemblyName, string resourceName )
		{
			Microsoft.Practices.Unity.Utility.Guard.ArgumentNotNullOrEmpty( assemblyName, "assemblyName" );
			Microsoft.Practices.Unity.Utility.Guard.ArgumentNotNullOrEmpty( resourceName, "resourceName" );
			this.assemblyName = assemblyName;
			this.resourceName = resourceName;
		}

		public string AssemblyName
		{
			get { return assemblyName; }
		}

		public string ResourceName
		{
			get { return resourceName; }
		}

		public Stream ResolveStream( IBuilderContext context )
		{
			var result = Assembly.Load( AssemblyName ).GetManifestResourceStream( ResourceName );
			if ( result != null )
			{
				return result;
			}
			throw new InvalidOperationException( string.Format( "Could not find resource {0} in assembly {1}.", AssemblyName, ResourceName ) );
		}
	}
}